package com.zhny.aiot.hfdj.outage.alarm.plugin;

import com.zhny.aiot.hfdj.outage.alarm.plugin.model.OutageAlarmStoreEntry;
import com.zhny.aiot.plugin.ICenterFacilities;
import com.zhny.aiot.plugin.IDeviceFactory;
import com.zhny.aiot.plugin.core.utils.MessageUtils;
import com.zhny.aiot.plugin.modbus.ModemEngine;
import com.zhny.aiot.plugin.modbus.device.ModemConfig;
import com.zhny.aiot.plugin.modbus.device.ModemDevice;
import com.zhny.aiot.plugin.modbus.handler.model.ModemRequestMessage;
import com.zhny.aiot.plugin.modbus.handler.model.ModemResponseMessage;
import com.zhny.aiot.plugin.model.DeviceEntity;
import com.zhny.aiot.plugin.model.MessageEntry;
import com.zhny.aiot.plugin.model.MessageType;
import com.zhny.aiot.plugin.model.TaskEntity;

public class OutageAlarmDevice extends ModemDevice<OutageAlarmStoreEntry> {

    public OutageAlarmDevice(ModemEngine engine, IDeviceFactory<ModemConfig> factory, ICenterFacilities centerFacilities, DeviceEntity entity) {
        super (engine, factory, centerFacilities,entity);
    }

    @Override
    public void onDecoder(ModemResponseMessage msg) {
        if(checkError(msg)){
            OutageAlarmStoreEntry entry = new OutageAlarmStoreEntry ();
            int status = msg.getData ().readUnsignedShort ();
            String describe = status==0?"正常":"断电";
            entry.setStatus (describe);
            MessageEntry messageEntry =MessageUtils.createMessageEntry (this.getId ());
            messageEntry.setType (status==0? MessageType.RESULT:MessageType.ALARM);
            messageEntry.setData (entry);
            save (entry);
            nofity (messageEntry);
        }
    }

    public boolean checkError(ModemResponseMessage modemResponseMessage) {
        return modemResponseMessage.getData ().readableBytes () == 2;
    }

    @Override
    protected ModemRequestMessage getCommand(TaskEntity taskEntity) {
        return getFactory ().getRequestMessage (getConfig ());
    }

    @Override
    protected void disposable() {

    }
}
